package com.kfm.dingtalk.service.impl;

import com.kfm.dingtalk.service.ChatService;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatServiceImpl implements ChatService {

    @Value("${chat.key}")
    private String key;

    @Value("${chat.url}")
    private String host;


    @Override
    public String ask(String question) {
        return send(question);
    }


    private String send(String msg) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)// 自定义日志输出
                .addInterceptor(new OpenAiResponseInterceptor())// 自定义返回值拦截
                .connectTimeout(10, TimeUnit.SECONDS)// 自定义超时时间
                .writeTimeout(30, TimeUnit.SECONDS)// 自定义超时时间
                .readTimeout(30, TimeUnit.SECONDS)// 自定义超时时间
                .build();
        // 构建客户端
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey(Collections.singletonList(key))
                // 自定义key的获取策略：默认KeyRandomStrategy
                .okHttpClient(okHttpClient)
                // 自己做了代理就传代理地址，没有可不不传
                .apiHost(host)
                .build();
        // 聊天模型：gpt-3.5
        Message message = Message.builder().role(Message.Role.USER).content(msg).build();
        ChatCompletion chatCompletion = ChatCompletion.builder().messages(List.of(message)).build();
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        return chatCompletionResponse.getChoices().get(0).getMessage().getContent();
    }
}
